import qs from 'query-string'
import { message } from 'ant-design-vue'

const BASE_URL = 'http://localhost:8000'

async function request({
    url,
    options = {
        method: 'get',
        body: {}
    }
}){
    try {
        console.log(options);
        let curUrl = url.includes('http') ? url : BASE_URL + url
        if(options.method.toLowerCase() === 'get'){
            options.body && (
                options.body = qs.stringify(options.body)
            )
            curUrl = curUrl + '?' + options.body
        }else{
            options.body = JSON.stringify(options.body)
        }
        let res = await fetch(curUrl,options)

        const status = res.status

        let errorMsg = ''
        switch (status) {
            case 400 :
                errorMsg = '请求有误'
                break
            case 404:
                errorMsg = '服务未找到'
                break
            default:
                break
        }
        if(status > 500){
            errorMsg = '服务器有误'
        }
        if(errorMsg){
            throw errorMsg
        }

        res = await res.json()

        if(res.code !== 0){
            throw res.msg
        }

        return res

    } catch (error) {
        message.warn(error)
        message.config({ maxCount: 1 })
        console.log(error);
    }
}

export default request